import React from 'react';
import {naviPush} from '../../navigatorApp/actions';
import {connect} from 'react-redux';
import {setUserGuid , setUserName , setUserTeam , setDepCode} from '../main/actions';
import {View , Text  , TextInput , Button , Image , ImageBackground , Dimensions , TouchableOpacity , Platform,BackHandler} from 'react-native';
import {setBlueTooth  , toast, setConfigValue,getConfig , updateApp} from '../../utils/NativeUtil';
import themStyle  from  '../../config/themeStyle';
import themeConfig from '../../config/theme';
const {width , height} = Dimensions.get('window');
import CheckBox from 'react-native-checkbox';
import {login , bindClient , checkVersion} from './actions';
import config from '../../config/config';
const md5 = require('md5');
const checkedImage = require('../../image/icon_checkbox_press.png');
const checkImage = require('../../image/icon_checkbox_unpress.png');

class Login extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            // loginId:'05078161',
            loginId:'',
            password:'',
            // password:'1',
            c1_sel:false,
            c2_sel:false
        }
    }

    static navigationOptions = ({ navigation, screenProps }) => ({
        header: null
    });

    componentDidMount(){
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
        getConfig('c1',res=>{
            this.setState({
                    c1_sel: res.c1 == 1
                })

                if (res.c1 == 1){
                    getConfig('c1_text',res=>{
                        if(res.c1_text!=undefined){
                        this.setState({
                            loginId:res.c1_text
                        })
                    }
                    })
                }});

        
    

        getConfig('c2', res => {
            this.setState({
                c2_sel: res.c2 == 1
            })
            if (res.c2 == 1) {
                getConfig('c2_text', res => {
                    console.log(res);
                    if (res.c2_text != undefined) {
                        this.setState({
                            password: res.c2_text
                        })
                    }
                })
            }
        });

    
        let paramsV = {
            SystemType: Platform.OS == 'ios' ? 'ios' : 'android'
        }
        console.log(paramsV)
        checkVersion(paramsV).then(res => {
            if (res.length > 0){
                updateApp(res[0] , () => {});
            }
        }).catch(msg => {
            console.error(msg)
        });
      
            
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
      }

    handleBackPress = () => {
        BackHandler.exitApp();
    }
    toSet = () => {
        setBlueTooth(res => {
            console.log(res)
        });
    }

    loginAction = () => {
        console.log('props',this.props)
        if (this.state.loginId == '' ){
            toast('请输入用户名')
            return;
        }

        if (this.state.password == ''){
            toast('请输入密码')
            return;
        }

        if(this.state.c1_sel==true){
            setConfigValue('c1' , 1 )
        }else{
            setConfigValue('c1' , 0 )
        }
        setConfigValue('c1_text',this.state.loginId)

        if(this.state.c2_sel==true){
            setConfigValue('c2' , 1 )
            setConfigValue('c2_text',this.state.password)
        }else{
            setConfigValue('c2' , 0 )
        }

        let params = {
            UserName:this.state.loginId,
            Psd:this.state.password,
            MD5Psd: md5(this.props.userGuid + config.md5Secret)
        }
        console.log(params)

        login(params).then(res=>{
            console.log(res);
            if (res.length > 0 ){
                res = res[0]
                if(res!=''){

                    console.log(res);
                    this.bindClientAction(res.UserGuid);

                    setConfigValue('userguid',res.UserGuid);
                    setConfigValue('name',res.DisplayName);
                    setConfigValue('dpcode' ,res.DeptCode );

                    this.props.setUserGuid(res.UserGuid);
                    this.props.setUserName(res.DisplayName);
                    this.props.setUserTeam(res.DeptName);
                    this.props.setDepCode(res.DeptCode);
                    // 


                }
            } 
            this.props.naviPush('Main',{});
        }).catch(msg=>{
            console.log(msg);
        })
    }


    //绑定clientId
    bindClientAction = (userGuid) =>{
         getConfig("clientId" , res => {
             var clientId  = res.clientId;
             if (clientId.length > 0) {
                let params = {
                    UserGuid:userGuid,
                    ClientId : clientId
                }
                console.log(params);
                bindClient(params).then(res => {
                    console.log(res)
                }).catch(msg => {
                    console.error(msg)
                });
             }
         });
    }


    _c1=(e)=>{
        console.log(e)
        if (!e){
            this.setState({c1_sel:true})
        }else { 
            this.setState({c1_sel:false})
            setConfigValue('c1_text','')
        }
    }

    _c2=(e)=>{
        console.log(e)
        if(!e){
            this.setState({c2_sel:true})
        }else{
            this.setState({c2_sel:false})
            setConfigValue('c2_text','')
        }
    }
    render(){
        return <ImageBackground style={{flexDirection:'column' ,flex:1 , alignItems:'center'}} source={require('../../image/bg_loading.png')}>
            <Image 
                source={require('../../image/ico_logo.png')}
                style={{width:60 , height:67 , marginTop:50}}
            />

            <Text style={[themStyle.normalFontStyle,{marginTop:10 , backgroundColor:'transparent'}]}> 张家港市城管局 </Text>

            <Text style={[themStyle.bigFontStyle , {marginTop:10 , backgroundColor:'transparent'}]}>勤务管理系统</Text>

            <Text style={{color: themeConfig.blue3Color , fontSize:14 , marginTop:6 , backgroundColor:'transparent'}}>V1.0.1</Text>

            <View style={{marginLeft:30 , marginRight:30 ,  height:40 , width: width - 60 , marginTop:12 , 
            marginBottom:5,
            flexDirection:'row' , alignItems:'center'}}>

                <Text style={{color: themeConfig.blue3Color , fontSize:16 , marginRight:10 ,backgroundColor:'transparent'}}>工号</Text>

                <TextInput
                    style={{height: 40 , width:width - 100 , color:'white'}}
                    onChangeText={(text) => this.setState({loginId:text})}
                    underlineColorAndroid={'transparent'}
                    defaultValue={this.state.loginId}/>
            </View>

            <View style={{width: width - 60 , height:1 , backgroundColor:themeConfig.blue3Color}}></View>
            
            <View style={{marginLeft:30 , marginRight:30 ,    marginBottom:5,  height:40 , width: width - 60 , marginTop:12 , flexDirection:'row' , alignItems:'center'}}>
                <Text style={{color: themeConfig.blue3Color , fontSize:16 , marginRight:10 ,backgroundColor:'transparent'}}>密码</Text>
                <TextInput
                password={true}
                secureTextEntry={true}
                style={{height: 40 , width:width - 100 , color:'white'}}
                onChangeText={(text) => this.setState({password:text})}
                underlineColorAndroid={'transparent'}
                defaultValue={this.state.password}/>
            </View>
            
            <View style={{width: width - 60 , height:1 , backgroundColor:themeConfig.blue3Color}}></View>

            <View style={{width: width - 60 , flexDirection:'row' , alignItems:'center' , marginTop:20}}>
                <CheckBox 
                containerStyle={{marginRight:20}}
                labelStyle={{color:'white' , fontSize:14}}
                underlayColor={'transparent'}
                label="记住工号"
                labelLines={1}
                checkboxStyle={{width:18 , height:18 , marginRight:-5}}
                uncheckedImage={checkImage}
                checkedImage={checkedImage}
                checked={this.state.c1_sel}
                onChange={(e)=>this._c1(e)}></CheckBox>

                <CheckBox 
                labelStyle={{color:'white' , fontSize:14}}
                underlayColor={'transparent'}
                label="记住密码"
                labelLines={1}
                checkboxStyle={{width:18 , height:18 , marginRight:-5}}
                uncheckedImage={checkImage}
                checkedImage={checkedImage}
                checked={this.state.c2_sel}
                onChange={(e)=>this._c2(e)}></CheckBox>

            </View>


            <TouchableOpacity 
            onPress={this.loginAction}
            style={[themStyle.loginBtnStyle,{marginTop:25 }]}>
                <Text style={themStyle.loginTxtStyle}>登录</Text>
            </TouchableOpacity>
            
        </ImageBackground>
    }
}

const mapStateToProps = state => ({
    UserGuid: state.main.UserGuid
});

const mapDispatchToProps = dispatch => ({
    naviPush: (routeName, params) => {
        dispatch(naviPush(routeName, params));
    },
    setUserGuid: (userguid) => {
        dispatch(setUserGuid(userguid));
    },
    setUserName: (name) => {
        dispatch(setUserName(name));
    },
    setUserTeam: (team) => {
        dispatch(setUserTeam(team));
    },
    setDepCode:(code) => {
        dispatch(setDepCode(code));
    }
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Login);

